package com.zhou.www;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description OCR远程识别接口调用
 * @Author crzep
 * @Date 2020/10/29 11:04
 * @VERSION 1.0
 **/
public class OCRRpc {

    /**
     * ocr远程调用接口
     * @param webOcrUrl OCR远程调用接口
     * @param image 需要识别的图片
     * @return
     */
    public String toOcr(String webOcrUrl, File image){
        // 请求执行对象
        RestTemplate restTemplate = new RestTemplate();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //设置请求体，注意是LinkedMultiValueMap
        FileSystemResource fileSystemResource = new FileSystemResource(image);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        //用HttpEntity封装整个请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(webOcrUrl, files, String.class);
        // 处理返回信息
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        if (jsonObject.getInteger("code")==200){
            return jsonToOcrInfos(jsonObject.getJSONObject("data").getJSONArray("raw_out"));
        }
        return null;
    }

    /**
     * 将json转化为OCRinfo对象
     * @param jsonArray json数组
     * @return
     */
    public String jsonToOcrInfos(JSONArray jsonArray){
        List<OCRInfo> list=new ArrayList<>();
        String result="";
        for (int i=0;i<jsonArray.size();i++){
            JSONArray area= jsonArray.getJSONArray(i);
            OCRInfo ocrInfo=new OCRInfo();
            ocrInfo.setArea(JSON.parseArray(area.getString(0),Double.class));
            ocrInfo.setText(area.getString(1));
            ocrInfo.setPercent(area.getDouble(2));
            String re = ocrInfo.getText();
            if (re.length()>0){
                result+=re;
            }
        }
        return result;
    }

}
